package cn.edu.answer.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.answer.po.Student;
import cn.edu.answer.po.User;
import cn.edu.answer.service.UserService;
import cn.edu.answer.utils.Page;

/**
 * 用户控制器类
 */
@Controller
public class UserController {
	// 依赖注入
	@Autowired
	private UserService userService;

	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	public String login(String userName, String password, @RequestParam(value = "identity") String identity,
			Model model, HttpSession session) {
		// 通过账号和密码查询用户
		User user = userService.findUser(userName, password);
		
		String id = user.getIdentity();
		System.out.print(identity.equals(id));
		
		if(user != null && "教师".equals(id) && identity.equals(id)) {
			//将用户对象添加到Session 
			session.setAttribute("USER_SESSION", user);
			// 跳转到主页面
			return "teacher";
		}
		if(user != null && "管理员".equals(id) && identity.equals(id)) {
			//将用户对象添加到Session 
			session.setAttribute("USER_SESSION", user);
			// 跳转到主页面
			return "admin";
		}
		if(user != null && "学生".equals(id) && identity.equals(id)) {
			//将用户对象添加到Session 
			session.setAttribute("USER_SESSION", user);
			// 跳转到主页面
			return "student";
		}
		
		model.addAttribute("msg", "账号或密码或身份错误，请重新输入！");
		// 返回到登录页面
		return "login";
		}
	

	/**
	 * 退出登录
	 */
	@RequestMapping(value = "/logout.action")
	public String logout(HttpSession session) {
		// 清除Session
		session.invalidate();
		// 重定向到登录页面的跳转方式
		return "redirect:login.action";
	}

	/**
	 * 向用户登陆页面跳转
	 */
	@RequestMapping(value = "/login.action", method = RequestMethod.GET)
	public String toLogin() {
		return "login";
	}

	@RequestMapping(value = "/register.action", method = RequestMethod.GET)
	public String toRegister() {
		return "register";
	}

	/**
	 * 创建用户
	 */
	@RequestMapping("/user/createUser.action")
	@ResponseBody
	public String cateUser(User user, HttpSession session) {

		// 执行Service层中的创建方法，返回的是受影响的行数
		int rows = userService.createUser(user);
		if (rows > 0) {
			return "OK";
		} else {
			return "FAIL";
		}
	}
	
}
